import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Server {

	
	public static void main(String[] args) throws Exception {
		
		DatagramSocket server = new DatagramSocket(55555);
		DatagramPacket dp = new DatagramPacket(new byte[8192], 8192);
		
		String lastDate = null;
		FileOutputStream file = null;
		String newLine = System.getProperty("line.separator");
		
		while (true) {
			server.receive(dp);
			
			String name = null, msg = null;
			try {
				byte[] bytes = dp.getData();
				name = new String(bytes, 1, bytes[0]);
				msg = new String(bytes, 50, dp.getLength() - 50);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			String date = dateTime.split(" ")[0];
			String time = dateTime.split(" ")[1];
			
			
			System.out.println(name + "  " + time + newLine + "    " + msg);
	
			
			try {
				if (!date.equals(lastDate)) {
					lastDate = date;
					if (file != null)
						file.close();
					file = new FileOutputStream("c:/" + date + ".txt", true);
				}
				
				file.write((name + "  " + dateTime + newLine + "    " + msg + newLine).getBytes());
				file.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}
